// 检测浏览器中安装的字体
const getBrowserFonts = fontlist => {
  const availableFonts = new Set();
  fontlist.forEach((item, index) => {
    // addFontFace(fontlist);
    if (isFontAvailable(item.value, index)) {
      availableFonts.add(item.value);
    }
  });
  return availableFonts;
};

const isFontAvailable = fontName => {
  const canvas = document.createElement("canvas");
  const context = canvas.getContext("2d");
  canvas.width = 200;
  canvas.height = 100;

  const text =
    "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789&*一二三四五六七八九十零百千万上下左右中大大小小明暗春夏秋冬东南西北红黄蓝绿黑白";

  context.clearRect(0, 0, canvas.width, canvas.height);
  context.font = "72px Courier New";
  const defaultWidth = context.measureText(text).width;
  context.fillText(text, 10, 50);
  const defaultFontData = context.getImageData(
    0,
    0,
    canvas.width,
    canvas.height
  ).data;

  context.clearRect(0, 0, canvas.width, canvas.height);
  context.font = `72px ${fontName}, Courier New`;
  const newWidth = context.measureText(text).width;
  context.fillText(text, 10, 50);
  const testFontData = context.getImageData(
    0,
    0,
    canvas.width,
    canvas.height
  ).data;

  for (let i = 0; i < defaultFontData.length; i++) {
    if (defaultFontData[i] !== testFontData[i]) {
      return true;
    }
  }
  if (newWidth !== defaultWidth) return true;
  return false;
};

const addFontFace = fontlist => {
  const style = document.createElement("style");
  style.type = "text/css";
  let fontFace = ``;
  fontlist.forEach((item, index) => {
    fontFace += `@font-face {
                    font-family: 'MyCustomFont${index}';
                    src: local('${item.value}'), local('${item.name}') format('truetype');
                    font-weight: normal;
                    font-style: normal;
                  }
  `;
  });
  // const fontFace = `
  //               @font-face {
  //                   font-family: 'MyCustomFont';
  //                   src: local(华文隶书);
  //                   font-weight: normal;
  //                   font-style: normal;
  //               }
  // `;
  console.log(fontFace);
  style.appendChild(document.createTextNode(fontFace));
  document.head.appendChild(style);
};
// 初始化字体列表
const initializeFonts = async fontlist => {
  const availableFonts = getBrowserFonts(fontlist);
  fontlist.forEach(item => {
    if (!availableFonts.has(item.value)) {
      item.label = `${item.name} (下载)`;
      item.isDownload = true;
    } else {
      item.label = item.name;
    }
  });

  return fontlist;
};

export { getBrowserFonts, initializeFonts, addFontFace };
